import requests
from todo import Todo
import json

headers = {
    "Content-Type": "application/json"
}


class TodomanagerWithHttp:
    """
    通过 HTTP 访问服务器，来管理待办事项。数据不存储在本地，而是存储在远程服务器上
    """

    def __init__(self, host):
        self.host = host

    def get_url(self, url):
        return 'http://' + self.host + url

    def create(self, title: str):
        # 发送请求到 http://localhost:5000/todos
        data = json.dumps({"title": title})
        data = requests.post(self.get_url("/create_todo"), data=data, headers=headers).json()
        return Todo(**data)

    def get_list(self):
        data = requests.get(self.get_url("/todo")).json()
        return [Todo(**x) for x in data['todo']]

    def get_by_id(self, todo_id):
        data = json.dumps({"id": todo_id})
        data = requests.post(self.get_url(), data=data, headers=headers)
        return Todo(**data)

    def mark_completed(self, todo_id):
        data = json.dumps({"id": todo_id})
        data = requests.post(self.get_url("/mark_completed"), data=data, headers=headers)
        return self.get_list()
